<template>

    <div>
        <el-breadcrumb separator="/" style="color: black;font-weight: 700">
            <el-breadcrumb-item >首页</el-breadcrumb-item>
            <el-breadcrumb-item>航班查询</el-breadcrumb-item>
            <el-breadcrumb-item>航班时间</el-breadcrumb-item>
        </el-breadcrumb>
        <h1>航班时间信息查询</h1>
        <!--      搜索表单-->
        <el-row :gutter="20">
            <el-col :span="6">
                <el-button type="primary" @click="openAddDialog" style="display: none">添加</el-button>
            </el-col>
            <el-col :span="6">
                <el-form-item label="航班号" >
                    <el-input placeholder="航班号" v-model="searchCriteria.FLID" clearable />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item>
                    <el-button type="primary" @click="searchOnSubmit">查询</el-button>
                    <el-button @click="searchOnReset">取消</el-button>
                </el-form-item>
            </el-col>
        </el-row>

        <el-table :data="tableData" style="width: 100%">
            <el-table-column
                    :prop="item.prop"
                    :label="item.label"
                    v-for="(item, index) in tableHeader"
                    :key="item.prop"
            >
                <template #default="scope">
                    <div
                            v-show="item.editable || scope.row.editable"
                            class="editable-row"
                    >
                        <template v-if="item.type === 'input'">
                            <el-input
                                    v-bind="{ readonly: ['ID', 'FLID'].includes(item.prop) && scope.row.editable }"
                                    size="small"
                                    v-model="scope.row[item.prop]"
                                    :placeholder="`请输入${item.label}`"
                                    @change="handleEdit(scope.$index, scope.row)"
                            />
                        </template>
                        <template v-if="item.type === 'date'">
                            <el-date-picker
                                    v-model="scope.row[item.prop]"
                                    type="datetime"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    :placeholder="`请输入${item.label}`"
                                    @change="handleEdit(scope.$index, scope.row)"
                            />
                        </template>


                    </div>
                    <div
                            v-show="!item.editable && !scope.row.editable"
                            class="editable-row"
                    >
                        <span class="editable-row-span">{{ scope.row[item.prop] }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
<!--                    <el-button-->
<!--                            v-show="!scope.row.editable"-->
<!--                            size="small"-->
<!--                            @click="scope.row.editable = true"-->
<!--                            style="display: none"-->
<!--                    >编辑</el-button-->
<!--                    >-->
                    <el-button
                            v-show="scope.row.editable"
                            size="small"
                            type="success"
                            @click="saveEditedRow(scope.row)"
                            style="display: none"
                    >确定</el-button
                    >
<!--                    <el-button-->
<!--                            v-show="!scope.row.editable"-->
<!--                            size="small"-->
<!--                            type="danger"-->
<!--                            @click="deleteFlightData(scope.row.ID)"-->
<!--                            style="display: none"-->
<!--                    >删除</el-button-->
<!--                    >-->
                    <el-button
                            v-show="scope.row.editable"
                            size="small"
                            type="warning"
                            @click="cancelEdit(scope.row)"
                            style="display: none"
                    >取消</el-button
                    >
                    <el-button
                            size="small"
                            type="warning"
                            disabled
                    >您没有任何操作权限</el-button
                    >
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页组件示例 -->
      <el-pagination
          v-model="currentPage"
          :small="small"
          :disabled="disabled"
          :background="background"
          :page-size="pageSize"
          layout="prev, pager, next, jumper"
          :total=totalElements
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          v-if="showPagination"
      />
        <!-- 添加航班信息模态框 -->
        <el-dialog v-model="dialogVisible" title="添加航班信息" width="50%" @close="resetAddForm">
            <el-form ref="addFormRef" :model="newFlight" label-width="80px">
                <el-form-item label="航班号">
                    <el-input v-model="newFlight.flid" />
                </el-form-item>
                <el-form-item label="航班标识">
                    <el-input v-model="newFlight.fide" />
                </el-form-item>
                <el-form-item label="起飞时间">
                    <el-date-picker
                            v-model="newFlight.frtt"
                            type="datetime"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            placeholder="选择日期"
                    />
                </el-form-item>
                <el-form-item label="到达时间">
                    <el-date-picker
                            v-model="newFlight.frlt"
                            type="datetime"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            placeholder="选择日期"
                    />
                </el-form-item>
                <!-- 其他字段... -->
            </el-form>
            <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onAddHandler">确定</el-button>
      </span>
            </template>
        </el-dialog>
    </div>
</template>


<script setup>
    import { ref, reactive, onMounted,onUpdated,computed,nextTick } from 'vue';
    import {ElMessage, ElMessageBox} from 'element-plus'
    import axios from 'axios'; // 确保已导入axios
    const small = ref(false)
    const background = ref(true)
    const disabled = ref(false)

    const handleSizeChange = (val) => {
      console.log(`${val} items per page`)
    }
    const item = reactive({
        ID: '',
        FLID: '',
        FIDE: "",
        FRTT: "",
        FRLT: '',
        VALID: "",
        displayStatus:"",
    });

    const header = {
        prop: "key",
        label: "自定义",
        editable: false,
        type: "input",
    };

    const tableHeader = ref([

        {
            prop: "FLID",
            label: "航班号",
            editable: false,
            type: "input"
        },
        {
            prop: "FIDE",
            label: "航班标识",
            editable: false,
            type: "input"
        },
        {
            prop: "FRTT",
            label: "起飞时间",
            editable: false,
            type: "date"
        },
        {
            prop: "FRLT",
            label: "到达时间",
            editable: false,
            type: "date"
        },
        {
            prop: "displayStatus",
            label: "状态",
            editable: false,
            type: "select", // 将类型更改为'select'
            options: [
                { label: "启用", value: 1 },
                { label: "禁用", value: 0 },
            ],
        },
    ]);

    const tableData = ref([]);


    const showPagination = ref(true);

    //精准查询
    const searchCriteria = reactive({
        FLID: "",
    });

    //分页相关状态
    const currentPage = ref(1); // 当前页码，默认为第一页
    const pageSize = ref(5); // 每页显示数量，默认为5条
    const totalElements = ref(0);

    // 初始化时加载第一页数据
    onMounted(() => {
        fetchFlightData();
        showPagination.value = true;
    });
    onUpdated(() => {
    });

    // 添加分页导航的处理函数，比如上一页、下一页、跳转到特定页
    function handleCurrentChange(page) {
        currentPage.value = page;
        fetchFlightData(page);
    }


    // 更新fetchUserData函数以支持分页查询
    async function fetchFlightData(current = currentPage.value, size = pageSize.value) {
        try {
            const response = await axios.get('/view/page', {
                params: {
                    currentPage: current,
                    pageSize: size
                }
            });
            if (!response.data.errorCode || response.data.errorCode === "200") {
                // 更新tableData时，考虑分页数据结构
                //将接口返回的数据通过map方法遍历并转换为新的对象数组
                tableData.value = response.data.data.map(flightView => ({
                    ID: flightView.id,
                    FLID: flightView.flid,
                    FIDE: flightView.fide,
                    FRTT: flightView.frtt,
                    FRLT: flightView.frlt,
                    VALID: flightView.valid,
                    // 添加新属性用于展示，根据VALID值决定
                    displayStatus: flightView.valid === 1 ? '启用' : '禁用',
                    editable: false,
                }));
                totalElements.value = response.data.total;
            } else {
                ElMessage.error(response.data.msg || '获取数据失败');
                console.error('Failed to fetch data. ErrorCode:', response.data.errorCode, ', Message:', response.data.msg);
            }
        } catch (error) {
            ElMessage.error('获取数据过程中发生错误');
            console.error('Error fetching data:', error);
        }
    }

    // 搜索条件
    async function searchOnSubmit() {
        if (!searchCriteria.FLID) {
            ElMessage.warning('请输入航班号');
            return;
        }
        if (!/^[1-9]\d{5}$/.test(searchCriteria.FLID)) {
            ElMessage.warning('航班号格式不正确，请输入正确的格式[六位数字]');
            return;
        }
        try {
            const response = await axios.get(`/view/find`, {
                params: {
                    FLID: searchCriteria.FLID,
                },
            });

            if (response.data.errorCode === "200") {
                // 映射到tableData中
                tableData.value = response.data.data.map(flightView => ({
                    ID: flightView.id,
                    FLID: flightView.flid,
                    FIDE: flightView.fide,
                    FRTT: flightView.frtt,
                    FRLT: flightView.frlt,
                    VALID: flightView.valid,
                    // 添加新属性用于展示，根据VALID值决定
                    displayStatus: flightView.valid === 1 ? '启用' : '禁用',
                    editable: false,
                }));
                //    查询成功后把查询的结果添加到表单展示
                showPagination.value = false;
            } else {
                ElMessage.error('查询失败，请检查输入或重试');
                console.error('查询失败:', response.data.message || '未提供错误信息');
            }
        } catch (error) {
            ElMessage.error('查询过程中发生错误');
            console.error('查询错误:', error);
        }
    }

    // 添加航班信息的对话框状态
    const dialogVisible = ref(false);

    // // 定义验证规则
    // const addFormRules = computed(() => ({
    //   frtt: [{ required: true, message: '起飞时间不能为空', trigger: 'blur' }],
    //   frlt: [{ required: true, message: '降落时间不能为空', trigger: 'blur' }],
    // }));

    // 新航班信息对象
    const newFlight = reactive({
        flid:"",
        fide : "",
        frtt : "",
        frlt : "",
    });

    // 添加表单的引用
    const addFormRef = ref( null);

    // 打开添加航班信息的模态框
    const openAddDialog = () => {
        dialogVisible.value = true;
    };

    // 重置添加表单
    const resetAddForm = () => {
        newFlight.flid = "";
        newFlight.fide = "";
        newFlight.frtt = "";
        newFlight.frlt = "";
    };

    // 添加航班信息的处理函数
    async function onAddHandler() {
        try {
            // 验证表单
            if (!addFormRef.value) return;
            // await addFormRef.value.validate('submit');
            //  校验航班号必须是6位的数字
            if (!/^[1-9]\d{5}$/.test(newFlight.flid)) {
                ElMessage.warning('航班号格式不正确，请输入正确的格式[六位数字]');
                return;
            }

            // 发送添加请求到后端
            const response = await axios.post('/view/insert', newFlight);

            if (!response.data.errorCode || response.data.errorCode === "200") {
                ElMessage.success('添加成功');
                dialogVisible.value = false; // 关闭模态框
                await fetchFlightData(); // 刷新表格数据
            } else {
                ElMessage.error(response.data.msg || '添加失败，请重试');
            }
        } catch (error) {
            console.error('Error adding data:', error);
            ElMessage.error('添加过程中发生错误');
        }
    }

    // 删除航班信息
    async function deleteFlightData(ID) {
        // 使用ElMessageBox显示确认对话框
        const confirmResult = await ElMessageBox.confirm(
            '确定要删除这条航班信息吗？',
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        // 如果用户点击了确认按钮（confirm）
        if (confirmResult === 'confirm') {
            try {
                const response = await axios.delete(`/view/${ID}`);

                if (!response.data.errorCode || response.data.errorCode === "200") {
                    await fetchFlightData();
                    ElMessage.success('删除成功');
                } else {ElMessage.error('删除失败，请重试');}
            } catch (error) {
                console.error('Error deleting data:', error);
                ElMessage.error('删除失败');
            }
        }
        // 如果用户点击取消，则什么都不做，对话框自动关闭
    }

    //取消查询
    const searchOnReset = async () => {
        showPagination.value = true;
        searchCriteria.FLID = "";
        await fetchFlightData();
    };
    //切换表格行进入编辑模式
    function handleEdit(row) {
        row.editable = true;
    }


    // 修改
    async function saveEditedRow(row) {
        try {
            const updatedFlight = {
                id: row.ID,
                flid: row.FLID,
                fide: row.FIDE,
                frtt: row.FRTT,
                frlt: row.FRLT,
            };
            const response = await axios.put(`/view/update`, updatedFlight);

            if (!response.data.errorCode || response.data.errorCode === "200") {
                ElMessage.success('更新成功');
                row.editable = false;
                await fetchFlightData();
            } else {
                ElMessage.error(response.data.msg || '更新失败，请重试');
            }
        } catch (error) {
            console.error('Error updating data:', error);
            ElMessage.error('更新过程中发生错误');
        }
    }
    //取消修改按钮
    const cancelEdit = (row) => {
        row.editable = false;
        //    恢复原来数据
        Object.assign(row, {
            ID: row.ID,
            FLID: row.FLID,
            FIDE: row.FIDE,
            FRTT: row.FRTT,
            FRLT: row.FRLT,
        });
        ElMessage.warning('已取消修改');
        fetchFlightData();
    };
</script>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 20px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>